//
//  NSString+ZXMD5.m
//  Runner
//
//  Created by simon on 2021/8/4.
//

#import "NSString+ZXMD5.h"

#import <CommonCrypto/CommonDigest.h>

@implementation NSString (ZXMD5)

//为什么字母都是大写的？
+ (NSString *)zx_createdMD5String:(NSString *)key
{
    const char *str = [key UTF8String];//转换成utf-8
    unsigned char result[CC_MD5_DIGEST_LENGTH];//开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    CC_MD5(str,  (CC_LONG)strlen(str), result);
    NSMutableString *hash = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    for (int i =0; i<CC_MD5_DIGEST_LENGTH; i++)
    {
        [hash appendFormat:@"%02X",result[i]];// x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
    }
    return [hash lowercaseString];
}


+ (NSString *)zx_creatMD5StringWithDict:(NSDictionary *)dict sortKeyArray:(NSArray *)sortKeys
{
    __block NSString *str = @"";
    [sortKeys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        id value = [dict objectForKey:obj];
        if([str length] !=0) {
            str = [str stringByAppendingString:@"&"];
        }
        str = [str stringByAppendingFormat:@"%@=%@",obj,value];
    }];
    
    NSString *md5String = [NSString zx_createdMD5String:str];
    return md5String;
}



@end
